import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';
import { HttpResponse } from '@/types/global';
import useUser from '@/hooks/user';

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = getToken();
    if (!config.headers) {
      config.headers = {};
    }
    config.headers.token = `${token}`;
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;
    if (!res.isSuccess) {
      Message.error({
        content: res.resultMsg || '服务器错误，请稍候重试',
        duration: 5 * 1000,
      });
      return Promise.reject(
        new Error(res.resultMsg || '服务器错误，请稍候重试')
      );
    }
    return {
      data: res,
    };
  },
  (error) => {
    if (error.response.status === 401) {
      Modal.confirm({
        title: '已退出',
        content: '用户认证已过期，需要重新登录（或停留在该页面）',
        cancelText: '停留在该页面',
        okText: '重新登录',
        async onOk() {
          const { logout } = useUser();

          await logout();
        },
      });
    } else {
      Message.error({
        content: error.msg || 'Request Error',
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);
